package com.eqdd.yiqidian.ui.tongxunlu;

import android.databinding.DataBindingUtil;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.TeamCheatCreateActvitiyCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseQuickAdapter;
import com.eqdd.yiqidian.adapter.recycleadapter.BaseViewHolder;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseApplication;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.BaseBean;
import com.eqdd.yiqidian.bean.rebuild.FriendListResultBean;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.listener.OnMyClickListener;
import com.eqdd.yiqidian.utils.GsonUtils;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.PinYinUtil;
import com.eqdd.yiqidian.widget.QuickIndexBar;
import com.lqr.recyclerview.LQRRecyclerView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

import static com.eqdd.yiqidian.R.id.ivHeader;

public class TeamCheatCreateActvitiy extends BaseActivity {

    public static final String ADD_TEAM_MEMBER = "add_team_member";//拉人入群
    private boolean isAddTeamMemberMode = false;//标记当前是否是拉人入群模式（默认是创建群）
    private List<String> mSelectedTeamMemberAccounts = new ArrayList<>();//已经在群中的成员账号

    private List<FriendListResultBean> mContacts = new ArrayList<>();
    private int i;

    private List<FriendListResultBean> mSelectedContacts = new ArrayList<>();//选中的联系人
    private TeamCheatCreateActvitiyCustom dataBinding;

    @InjectView(R.id.rvSelectedContacts)
    LQRRecyclerView mRvSelectedContacts;
    @InjectView(R.id.etKey)
    EditText mEtKey;
    @InjectView(R.id.vTop)
    View mVTop;

    @InjectView(R.id.rvContacts)
    LQRRecyclerView mRvContacts;
    @InjectView(R.id.quickIndexBar)
    QuickIndexBar mQuickIndexBar;
    @InjectView(R.id.tvLetter)
    TextView mTvLetter;

    private Drawable mSearchDrawable;


    private View mHeaderView;
    private TextView mTvSelectOneGroup;
    private TextView mTvCreateGroupFaceToFace;
    private BaseQuickAdapter<FriendListResultBean, BaseViewHolder> quickAdapter;
    private BaseQuickAdapter<FriendListResultBean, BaseViewHolder> mSelectedQuickAdapter;
    private String groupid;
    private String groupname;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_team_cheat_create_actvitiy);
        ButterKnife.inject(this);

        initTopTitleBar(View.VISIBLE, "拉人入群");
        initTopRightText("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new HttpPresneter.Builder(HttpConfig.ADD_GROUP, String.class, TeamCheatCreateActvitiy.this)
                        .Params("userGuid", getUids())
                        .Params("Groupid", groupid)
                        .Params("GroupName", groupname)
                        .setOnHttpListener(new HttpPresneter.OnHttpListener() {
                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(Object o) {
                                if (((String) o).contains("200")) {
                                    setResult(Config.CHANGE);
                                    finish();
                                }
                            }
                        })
                        .build()
                        .post();
            }
        });
        initHeaderView();
        //得到搜索框的左图标
        mSearchDrawable = BaseApplication.getApplication().getResources().getDrawable(R.mipmap.ic_search1);
        mSearchDrawable.setBounds(0, 0, mSearchDrawable.getMinimumWidth(), mSearchDrawable.getMinimumHeight());
    }

    private String getUids() {
        String uids = "";
        for (int i = 0; i < mSelectedContacts.size(); i++) {
                uids += ";"+mSelectedContacts.get(i).getGuid();
        }
        return uids;
    }

    @Override
    public void initData() {
        //已经在群中的成员账号
        groupid = getIntent().getStringExtra("groupid");
        groupname = getIntent().getStringExtra("groupname");
        ArrayList<String> stringArrayListExtra = getIntent().getStringArrayListExtra(ADD_TEAM_MEMBER);
        if (stringArrayListExtra == null) {
            isAddTeamMemberMode = false;
        } else {
            isAddTeamMemberMode = true;
            mSelectedTeamMemberAccounts.addAll(stringArrayListExtra);
        }
        new HttpPresneter.Builder(HttpConfig.FRIEND_LIST_INFO, String.class, this)
                .Params("userGuid", user.getGuid())
                .setOnHttpListener(new HttpPresneter.OnHttpListener() {
                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Object o) {
                        BaseBean<FriendListResultBean> beans =
                                GsonUtils.changeGsonToBaseBean((String) o, FriendListResultBean.class);
                        mContacts = beans.getItems();
                        //对集合排序
                        Collections.sort(mContacts);
                        setContactsAdapter();
                    }
                })
                .build()
                .post();
        setSelectedContactsAdapter();
    }

    @Override
    public void setView() {
        mQuickIndexBar.setListener(new QuickIndexBar.OnLetterUpdateListener() {
            @Override
            public void onLetterUpdate(String letter) {
                //显示字母提示
                showLetter(letter);

                //滑动对对应字母条目处
                if ("↑".equalsIgnoreCase(letter)) {
                    mRvContacts.moveToPosition(0);
                } else if ("☆".equalsIgnoreCase(letter)) {
                    mRvContacts.moveToPosition(0);
                } else {
                    //找出第一个对应字母的位置后，滑动到指定位置
                    for (i = 0; i < mContacts.size(); i++) {
                        FriendListResultBean contact = mContacts.get(i);
                        String c = PinYinUtil.getPinyin(contact.getUpname()).charAt(0) + "";
                        if (c.equalsIgnoreCase(letter)) {
                            mRvContacts.moveToPosition(i);
                            break;
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    private void initHeaderView() {
        mHeaderView = View.inflate(this, R.layout.header_group_cheat_rv, null);
        mTvSelectOneGroup = mHeaderView.findViewById(R.id.tvSelectOneGroup);
        mTvCreateGroupFaceToFace = mHeaderView.findViewById(R.id.tvCreateGroupFaceToFace);
    }

    /**
     * 设置联系人列表适配器
     */
    private void setContactsAdapter() {
        quickAdapter = new BaseQuickAdapter<FriendListResultBean, BaseViewHolder>(R.layout.item_contact_cv, mContacts) {

            @Override
            protected void convert(BaseViewHolder helper, FriendListResultBean item) {
                int position = helper.getPosition() - quickAdapter.getHeaderLayoutCount();
                System.out.println(position);
                helper.setText(R.id.tvName, TextUtils.isEmpty(item.getUpname()) ? item.getUname() : item.getUpname());
                if (!TextUtils.isEmpty(item.getIphoto())) {
                    ImageUtil.setCircleImage(item.getIphoto(), helper.getView(ivHeader));
                } else {
                    helper.setImageResource(ivHeader, R.mipmap.ic_launcher);
                }
                String str = "";
                //得到当前字母
                String currentLetter = PinYinUtil.getPinyin(item.getUpname()).charAt(0) + "";

                if (position == 0) {
                    str = currentLetter;
                } else {
                    //得到上一个字母
                    String preLetter = PinYinUtil.getPinyin(mContacts.get(position - 1).getUpname()).charAt(0) + "";
                    //如果和上一个字母的首字母不同则显示字母栏
                    if (!preLetter.equalsIgnoreCase(currentLetter)) {
                        str = currentLetter;
                    }

                    int nextIndex = position + 1;
                    if (nextIndex < mContacts.size() - 1) {
                        //得到下一个字母
                        String nextLetter = PinYinUtil.getPinyin(mContacts.get(nextIndex).getUpname()).charAt(0) + "";
                        //如果和下一个字母的首字母不同则隐藏下划线
                        if (!nextLetter.equalsIgnoreCase(currentLetter)) {
                            helper.setVisible(R.id.vLine, false);
                        } else {
                            helper.setVisible(R.id.vLine, true);
                        }
                    } else {
                        helper.setVisible(R.id.vLine, false);
                    }
                }
                if (position == mContacts.size() - 1) {
                    helper.setVisible(R.id.vLine, false);
                }

                //根据str是否为空决定字母栏是否显示
                if (TextUtils.isEmpty(str)) {
                    helper.setVisible(R.id.tvIndex, false);
                } else {
                    helper.setVisible(R.id.tvIndex, true);
                    helper.setText(R.id.tvIndex, currentLetter);
                }


                final CheckBox cb = helper.getView(R.id.cb);
                helper.setVisible(R.id.cb, true);

                if (isAddTeamMemberMode) {
                    //判断当前的联系人是否已经在群中，是则显示灰色勾选图标
                    if (mSelectedTeamMemberAccounts.contains(item.getUname())) {
                        cb.setEnabled(false);
                        cb.setChecked(true);
                    } else {
                        cb.setEnabled(true);
                    }
                }

                //条目点击勾选好友
                helper.getView(R.id.root).setOnClickListener(new OnMyClickListener(position) {
                    @Override
                    public void onClick(View v) {
                        if (isAddTeamMemberMode) {
                            //判断当前的联系人是否已经在群中，是否点击无效
                            if (mSelectedTeamMemberAccounts.contains(quickAdapter.getItem(getPosition()).getUname())) {
                                return;
                            }
                        }

                        if (cb.isChecked()) {
                            cb.setChecked(false);
                            //去掉选中项
                            mSelectedQuickAdapter.remove(quickAdapter.getItem(getPosition()));
                        } else {
                            cb.setChecked(true);
                            //增加选中项
                            mSelectedQuickAdapter.addData(quickAdapter.getItem(getPosition()));
                        }
                        dataBinding.includeTitle.tvRight.setText("确定" + (mSelectedContacts.size() > 0 ? "(" + mSelectedContacts.size() + ")" : ""));
                        //根据选中联系人的个数显隐藏搜索框左图标
                        if (mSelectedContacts.size() > 0) {
                            mEtKey.setCompoundDrawables(null, null, null, null);
                        } else {
                            mEtKey.setCompoundDrawables(mSearchDrawable, null, null, null);
                        }
                    }
                });

            }
        };

        //加入头部
//        quickAdapter.addHeaderView(mHeaderView);
        dataBinding.rvContacts.setAdapter(quickAdapter);
//        //设置适配器
//        if (mRvContacts != null)
//            mRvContacts.setAdapter(quickAdapter.getHeaderAndFooterAdapter());
    }

    /**
     * 设置被选中联系人头像列表适配器
     */
    private void setSelectedContactsAdapter() {
//        for (int i = 0; i < 10; i++) {
//            mSelectedContacts.add(new Contact());
//        }
        if (mSelectedQuickAdapter == null) {
            mSelectedQuickAdapter = new BaseQuickAdapter<FriendListResultBean, BaseViewHolder>(R.layout.item_selected_contact_rv, mSelectedContacts) {

                @Override
                protected void convert(BaseViewHolder helper, FriendListResultBean item) {

                    //动态设置列表宽度
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mRvSelectedContacts.getLayoutParams();
//                    params.weight = mSelectedContacts.size() > 5 ? 4 : 0;
                    int parentWidth = ((LinearLayout) mRvSelectedContacts.getParent()).getWidth();
                    int childWidth = parentWidth * 4 / 5;
                    params.width = mSelectedContacts.size() > 5 ? childWidth : ViewGroup.LayoutParams.WRAP_CONTENT;
                    mRvSelectedContacts.setLayoutParams(params);

                    ImageView ivHeader = helper.getView(R.id.ivHeader);
                    if (TextUtils.isEmpty(item.getIphoto())) {
                        ivHeader.setImageResource(R.mipmap.ic_launcher);
                    } else {
                        ImageUtil.setCircleImage(item.getIphoto(), ivHeader);
                    }
                }
            };


            mRvSelectedContacts.setAdapter(mSelectedQuickAdapter);
        } else {
            mSelectedQuickAdapter.notifyDataSetChanged();
        }
    }


    /**
     * 显示所触摸到的字母
     *
     * @param letter
     */
    protected void showLetter(String letter) {
        mTvLetter.setVisibility(View.VISIBLE);// 设置为可见
        mTvLetter.setText(letter);

        Observable.timer(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((i) ->
                        mTvLetter.setVisibility(View.GONE)
                );

    }
}
